package com.kerbores.kop.filter;

import org.nutz.ioc.Ioc;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ServerRedirectView;

/**
 * KOP 会话保持处理器
 * 
 * @author wkipy
 *
 */
public abstract class KopSessionKeepFilter implements ActionFilter {

	protected Ioc ioc;

	private String path;

	public KopSessionKeepFilter(String path) {
		super();
		this.path = path;
	}

	@Override
	public View match(ActionContext ac) {
		ioc = ac.getIoc();
		if (null == ac.getMethod().getAnnotation(IgnoreSessionKeep.class) || !ac.getMethod().getAnnotation(IgnoreSessionKeep.class).igonre()) {
			String uuid = Mvcs.getReq().getHeader("uuid");
			// 处理session
			if (!addUUIDSessionedObject(uuid)) {
				return new ServerRedirectView(path);
			}
		}
		// 填充header
		Mvcs.getResp().addHeader("uuid", getKOPSessionKey());

		return null;
	}

	/**
	 * 获取kop session 保持的键
	 * 注意此键和addUUIDSessionedObject的参数对应也就是下次请求将这个返回值参入进行session创建处理
	 * 
	 * @return
	 */
	protected abstract String getKOPSessionKey();

	/**
	 * 根据这个UUID处理Session相关的逻辑,注意UUID可能是空的哟!
	 * 
	 * @param uuid
	 * @return
	 */
	protected abstract boolean addUUIDSessionedObject(String uuid);

}
